<template>
  <div class="demo-block">
    <!-- 演示区域 -->
    <div class="demo-preview">
      <component :is="comp"></component>
    </div>

    <!-- 分割线 -->
    <div class="demo-divider"></div>
    <!-- 代码区域 -->
    <div class="demo-code-wrap">
      <div class="demo-code-operate">
        <span>复制</span><span>展开</span>
      </div>
      <div class="demo-code-content">
        <pre class="demo-code">
          <code v-html="code"></code>
        </pre>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useData } from "vitepress";
import { highlight, languages } from "prismjs";
import "prismjs/themes/prism.css";

const modules = import.meta.glob("@/components/*/__demo__/*.vue");
const rawModules = import.meta.glob("@/components/*/__demo__/*.vue", {
  as: "raw",
});

const props = defineProps<{ file: string }>();

const comp = ref();

const source = ref("");

const code = ref("");

onMounted(async () => {
  const key = `../src/components/${props.file}`;

  const importer = modules[key];
  const rawImporter = rawModules[key];
  if (!importer || !rawImporter) {
    console.error(`未找到 demo 文件: ${props.file}`);
  }

  const component = await importer();
  const rowSource = await rawImporter();
  console.log(component.default, modules, key, rowSource);
  comp.value = component.default;
  source.value = rowSource;
  code.value = highlight(source.value, languages.html, "html");
  //   hightlightedCode.value = highlight(source.value, languages.html, "html");
});
</script>
<style lang="less" scoped>
.demo-block {
  border: 1px solid #eaeaea;
  border-radius: 6px;
  margin: 16px 0;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.demo-preview {
  padding: 16px;
}

.demo-divider {
  height: 1px;
  background: #f0f0f0;
}

.demo-code-operate {
  display: flex;
  justify-content: flex-end;
  padding: 6px 12px;
  background: #f9f9f9;
  gap: 8px;
  background-color: #fff;
}

.demo-code {
  box-sizing: border-box;
  height: auto;
  padding: 12px;
  margin: 0;
  background: #f9f9f9;
  font-size: 13px;
  color: #333;
  overflow-x: auto;
}

.demo-code-content {
  height: auto;
  overflow: hidden;
  &.down {
    height: 0;
  }
}
</style>
